package com.jingwu.example.repo;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jingwu.example.mapper.BookCategoryMapper;
import com.jingwu.example.mapper.BookMapper;
import com.jingwu.example.pojo.entity.BookDO;
import com.jingwu.example.pojo.query.AuthorQuery;
import com.jingwu.example.pojo.query.BookQuery;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author jingwu
 * @since 2021/2/1
 */
@Repository
public class BookRepository {

    @Resource
    private BookMapper mapper;
    @Resource
    private BookCategoryMapper relationMapper;


    public Page<BookDO> selectPage(BookQuery query) {
        Page<BookDO> page = new Page<>(query.getIndex(), query.getSize());
        this.mapper.selectPage(page, toWrapper(query));
        return page;
    }

    public BookDO selectById(Integer id) {
        return this.mapper.selectById(id);
    }

    public List<BookDO> select(BookQuery query) {
        return this.mapper.selectList(toWrapper(query));
    }

    private LambdaQueryWrapper<BookDO> toWrapper(BookQuery query) {
        return new QueryWrapper<BookDO>()
                .lambda()
                .eq(StringUtils.isNoneBlank(query.getName()), BookDO::getName, query.getName());
    }

    public int insert(BookDO entity) {
        return this.mapper.insert(entity);
    }

    public boolean update(BookDO entity) {
        return this.mapper.updateById(entity) > 0;
    }

}
